package com.itobase.statusDetect.Util;

import com.itobase.statusDetect.Model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.Optional;

/**
 * @author htyu
 * @date 2019/5/6
 */
public class AuthUtil {

    public static Optional<User> getUser() throws Throwable {
        Subject subject = SecurityUtils.getSubject();
        return Optional.of(Optional.ofNullable((User) subject.getPrincipal()).orElseThrow(() -> new RuntimeException("请先登录")));
    }

    public static String getUsername() throws Throwable {
        return getUser().map(User::getName).orElseThrow(() -> new RuntimeException("请先登录"));
    }

    public static String getUserId() throws Throwable {
        return getUser().map(User::getId).orElseThrow(() -> new RuntimeException("请先登录"));
    }

    public static String getOrganizationId() throws Throwable {
        return getUser().map(User::getOrganizationID).orElseThrow(() -> new RuntimeException("请先登录"));
    }

    public static void anonymousLogin() {
        Subject subject = SecurityUtils.getSubject();
        String username = "anonymous";
        String password = "anonymous";
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println("匿名账号配置>>>>>>>>>>>>>>>>>>>>>>>>");
        subject.login(token);
    }
}
